﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Transactions;
using ThanNhanTao.Server.Entities;
using System.Data;
using System.Data.SqlClient;

namespace ThanNhanTao.Server
{
    public partial class BenhKemTheoBLL
    {
        bvdn_thannhantaoEntities entities;
        public BenhKemTheoBLL()
        {
            entities = ThanNhanTaoGlobalServer.bvdn_thannhantaoEntities;
        }

        public List<BenhKemTheo> SelectAllIdBenhNhanBenhKemTheo(int idBenhNhan)
        {
            List<BenhKemTheo> listBenhKemTheo = (from BenhKemTheot in entities.BenhKemTheos
                                            .Include("Dm_ChanDoan")
                                                 orderby BenhKemTheot.Dm_ChanDoan.MaChanDoan
                                                 where BenhKemTheot.IdBenhNhan == idBenhNhan
                                                 select BenhKemTheot).ToList();
            return listBenhKemTheo;
        }

        public List<BenhKemTheo> SelectAllBenhKemTheo()
        {
            List<BenhKemTheo> listBenhKemTheo = (from BenhKemTheot in entities.BenhKemTheos
                                                .Include("Dm_ChanDoan")
                                                 orderby BenhKemTheot.Dm_ChanDoan.MaChanDoan
                                                 select BenhKemTheot).ToList();
            return listBenhKemTheo;
        }


        public void SaveBenhKemTheo(List<BenhKemTheo> listBenhKemTheo, int idBenhNhan)
        {
            try
            {
                deleteBenhKemTheo(idBenhNhan);
                BenhKemTheo temp;
                foreach (BenhKemTheo bkTheo in listBenhKemTheo)
                {
                    temp = new BenhKemTheo();
                    temp.IdBenhKemTheo = GetBenhKemTheoSoIDMax() + 1;
                    temp.MaChanDoan = bkTheo.MaChanDoan;
                    temp.IdBenhNhan = idBenhNhan;
                    entities.AddToBenhKemTheos(temp);
                    entities.SaveChanges();
                }
            }
            catch { }
        }

        private void deleteBenhKemTheo(int idBenhNhan)
        {
            try
            {
                foreach (BenhKemTheo bkTheo in SelectAllIdBenhNhanBenhKemTheo(idBenhNhan))
                {
                    entities.DeleteObject(bkTheo);
                    entities.SaveChanges();

                }
            }
            catch { }
        }

        private int GetBenhKemTheoSoIDMax()
        {
            try
            {
                return entities.BenhKemTheos.Max(u => u.IdBenhKemTheo);
            }
            catch
            {
                return 0;
            }
        }
    }
}
